<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\CategoryRequest;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index(){
        $categories = Category::orderByDesc('id')->paginate(request('page_size', 10));

        return view('backend.category.index', compact('categories'));
    }

    public function create(){
        $categories = Category::all();
        return view('backend.category.create',compact('categories'));
    }

    public function store(
        CategoryRequest $request,
        Category $category
    ){
        $data = $request->only([
            'name','description','pid'
        ]);
        $data['user_id'] = auth('admin')->id();
        $category->fill($data)->save();
        //TODO::角色
        //$admin->roles()->sync($request->input('role_id', []));

        flash('分类添加成功', 'success');

        return back();
    }

    public function edit($id){
        $category = Category::findOrFail($id);

        //TODO::要区分下身份,是谁创建的分类
        $categories = Category::all();

        return view('backend.category.edit', compact( 'category','categories'));
    }

    public function update(CategoryRequest $request, $id)
    {
        $category = Category::findOrFail($id);

        $data = $request->only([
            'name','description','pid'
        ]);
        $data['user_id'] = auth('admin')->id();

        $category->fill($data)->save();

        //$administrator->roles()->sync($request->input('role_id', []));

        flash('分类编辑成功', 'success');

        return back();
    }

    public function destroy($id)
    {
        //TODO::判断该分类下是否有文章
        $category = Category::findOrFail($id);
        //if (! $admin->couldDestroy()) {
        //    flash('当前用户是超级管理员账户无法删除');
        //} else {
        $category->delete();
        flash('分类删除成功', 'success');
        //}

        return back();
    }
}
